/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析

var touch = require("mlib/evt/touch");
var ajax = require("mlib/io/ajax");
var when = require("mlib/util/when");

var showMessage = require("../layer/info");
var weuiAlert = require('../layer/weuialert');

var prizeRender = require("./prize.ejs");

module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
	var click = false;
	var reward = null;
	var units = null;
	var startbtn = null;
	var nodeprize = null;
	var chanceTimes = 0;
	var prize_result = null ;
	var falresult = '' ;
	
	
	
	var lottery = {
		index:-1,	//当前转动到哪个位置
		count:0,	//总共有多少个位置
		timer:0,	//setTimeout的ID，用clearTimeout清除
		speed:200,	//初始转动速度
		times:0,	//转动次数
		cycle:50,	//转动基本次数：即至少需要转动多少次再进入抽奖环节
		prize:-1,	//中奖位置
		
	}

    //-------------事件响应声明---------------
    var evtFuncs = {
			roller:function (){	
                if(this.getAttribute("disabled")){
					return ;
				}		
				//_czc.push(["_trackEvent", "活动", "抽奖", "点击抽奖按钮"]);				
                this.setAttribute("disabled","disabled");
				custFuncs.activityQuery().then(function(result) {
					if(result.error!=0){				
						weuiAlert(result.msg,{});
						startbtn.removeAttribute("disabled");
						return ;
					}
					chanceTimes--;		
                    if(chanceTimes==-1){
						startbtn.setAttribute("disabled","disabled");
					}					
					if(chanceTimes==0){
						nodeList.start.classList.add("disabled");
						nodeList.start.innerHTML = '已抽奖' ;
						
					}
					nodeList.times.innerHTML = ""+chanceTimes;
					click=true;					  
                   prize_result = result;
					if(result.data.iswinner==1){
						var prizeId = result.data.prize[0].id;
						falresult = parseInt(nodeprize["prize-"+prizeId]); 
						console.log(falresult);
						custFuncs.setStop(falresult); // 设置中几等奖											
					}else{
						custFuncs.setStop(5); 					
					}					
					custFuncs.roller();
				 })


			}
	}

    //-------------子模块实例化---------------
    var initMod = function(node) {
			chanceTimes = data.usertodayleft;
			if(Object.prototype.toString.call(node)=="[object String]"){
				reward = document.querySelector(node);
			}else{
				reward = node;
			}
			nodeprize ={};
			units = [].slice.call(reward.querySelectorAll(".lottery-unit")); // 查出所有的奖品元素
/*
 0   1     2
 3  star   5
 6 thanks  8
*/			
			units.sort(function(a,b){	 // 对所有的奖品元素按照索引进行排序array(0=>0,1=>1,2=>2,3=>5,4=>8,5=>thanks,6=>6,7=>3)			
				return a.dataset.index - b.dataset.index;
			});
			units.forEach(function(item,index){// 将所有的奖品元素跟奖品索引一一对应保存到一个对象中
				nodeprize["prize-"+item.dataset.id] = item.dataset.index;
			});
			console.log(nodeprize);
			startbtn = reward.querySelectorAll(".lottery-start");
			lottery.count = units.length;
	}

    //-------------绑定事件------------------
    var bindEvents = function() {		
		touch.on(startbtn,"tap",evtFuncs.roller);		
		touch.on(nodeList.winlayer,"tap",".closeBtn",function(e){
		  nodeList.winlayer.style.display = "none";
		});	

		
	}

    //-------------自定义函数----------------
    var custFuncs = {
		    roller:function(){	
		    	
				lottery.times += 1;
				custFuncs.roll();

				if (lottery.times > lottery.cycle+10 && lottery.prize==lottery.index) {
					clearTimeout(lottery.timer);
					lottery.prize=-1;
					lottery.times=0;
					click=false;
					setTimeout(custFuncs.showAlert, 1000);
				}else{
					if (lottery.times<lottery.cycle) {
						lottery.speed -= 10;
					}else if(lottery.times==lottery.cycle) {
						 //var index = falresult||5;"谢谢参与"固定位置时做法
						 lottery.prize = falresult;
					}else{
						if (lottery.times > lottery.cycle+10 && ((lottery.prize==0 && lottery.index==7) || lottery.prize==lottery.index+1)) {
							lottery.speed += 110;
						}else{
							lottery.speed += 20;
						}
					}
					if (lottery.speed<40) {
						lottery.speed=40;
					};
					//console.log(lottery.times+'^^^^^^'+lottery.speed+'^^^^^^^'+lottery.prize);
					lottery.timer = setTimeout(custFuncs.roller,lottery.speed);
				}
			},
			roll:function(){
				var index = lottery.index, count = lottery.count;
				
				index += 1;					
				if(index > count-1){
					index = 0;
				} 
				
				units.forEach(function(item,idx){
					if(index==idx){
						item.classList.add("active");
					}else{
						item.classList.remove("active");
					}
				});				
				lottery.index = index;
			},
			stop:function(index){
				lottery.prize=index;
			},
			setStop:function(status){
				custFuncs.stop(status);
			},
			showAlert:function(){
				nodeList.start.removeAttribute("disabled");
				that.unLock();

					if(prize_result.data.iswinner==1 && prize_result.data.prize[0].num !=0 && prize_result.data.prize[0].type != 8){ //如果已经没有抽奖的机会，直接提示
						//showMessage("您的抽奖机会已用完");
						var prizeObj = prize_result.data.prize[0];
						nodeList.winlayer.innerHTML = prizeRender({
							"iswinner":prize_result.data.iswinner,
							"num":prizeObj.num,
							"id":prizeObj.id,							
							"img":prizeObj.img,							
							"url":prizeObj.url,
							"type":prizeObj.type
						});						
					}else{
						nodeList.winlayer.innerHTML = prizeRender({
							"iswinner":prize_result.data.iswinner,
							"num":prize_result.data.prize[0].num,
							"type":prize_result.data.prize[0].type
						});				
					}
					nodeList.winlayer.style.display = "block";


			},
			activityQuery:function(){//
				if(that.isLock()) {
					return;
				}
				that.lock();
			    var defer = when.defer();				
				ajax({
					url: data.url.playApi,
					onSuccess: function(result) { 
						
						defer.resolve(result);
					},
					onError: function(xmlHttp) { 

						defer.reject("网络连接失败1");
						
					}, // 当访问出错，比如网络连接不上、解析内容失败时触发，超时也会触发
					onTimeout: function(xmlHttp) { }, // 超时触发
					onAbort: function() { } // 网络中断时触发
				});
				return defer.promise; // 注意不管如何，函数在return时一定要返回这个对象
			}



		
	}

    //-------------一切从这开始--------------
    var init = function(_data) {
        data = _data;
        // 根据数据初始化模块
        // opts["render"]({ "title": data["title"] });

        // 找到所有带有node-name的节点
        nodeList = parseModule(document.body);
        // 子模块实例化
        initMod(node);
        // 绑定事件
        bindEvents();
    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};